from django.shortcuts import render, HttpResponse, redirect
from app01.models import UserInfo, Department

# Create your views here.

def index(request):
    return HttpResponse("欢迎使用")


def user_list(request):
    return render(request, "user_list.html")


def tpl(request):
    name = "小哈"
    roles = ["保安", "CEO", "队长"]
    user_info = {"name": "小子", "salary": "10000", "role": "CEO",}
    return render(request, "tpl.html", {"n1": name, "n2": roles, "n3": user_info})


def something(request):

    # 获取请求方式
    print(request.method)

    # 在url上传递一些值
    print(request.GET)

    # 在请求体中发送数据
    print(request.POST)

    # [响应]return HttpResponse("返回内容")
    # [响应]return render(request, "something.html", {"title": "来了"})
    # [响应]让浏览器重定向到其他页面
    return redirect("https://www.baidu.com")


# 登录
def login(request):
    if request.method == "GET" :
        return render(request, "login.html")
    else:
        # print(request.POST)
        username = request.POST.get("user")
        password = request.POST.get("pwd")
        if username == "root" and password == "root":
            return HttpResponse("登陆成功")
        else:
            return render(request, "login.html", {"errinfo": "用户名或密码错误"})



# ORM操作
def orm(request):
    # 新建
    # Department.objects.create(title="销售部")
    # Department.objects.create(title="IT部")
    # Department.objects.create(title="运营部")

    # 删除
    # Department.objects.filter(id=2).delete()

    # 获取
    # []形式  QuerySet类型
    # data_list = UserInfo.objects.all()
    # for item in data_list:
    #     print(item.id, item.name, item.password, item.age)

    # 更新数据
    # Department.objects.all().update(title="haha")
    Department.objects.filter(id=3).update(title="IT部")


    return HttpResponse("成功")


def info_list(request):

    # 获取数据库所有对象信息
    data_list = UserInfo.objects.all()

    return render(request, "info_list.html", {"data_list": data_list})


def info_add(request):
    if request.method == 'GET':
        return render(request, "info_add.html")
    else:
        user = request.POST.get("user")
        pwd = request.POST.get("pwd")
        age = request.POST.get("age")
        UserInfo.objects.create(name=user, password=pwd, age=age)
        return redirect("/info/list")


def info_delete(request):
    nid = request.GET.get('nid')
    UserInfo.objects.filter(id=nid).delete()
    return redirect("/info/list")